package com.rzcoding.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rzcoding.dao.ManagerMapper;
import com.rzcoding.dto.base.ResultConst;
import com.rzcoding.dto.dao.ManagerRoleNameMo;
import com.rzcoding.entity.Manager;
import com.rzcoding.exception.BussinessException;
import com.rzcoding.util.BCrypt;
import com.rzcoding.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class ManagerService {

    @Autowired
    private ManagerMapper managerMapper;


    public PageInfo<ManagerRoleNameMo> selectByUsername(String userName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(managerMapper.selectByUsername(userName));
    }

    public String login(String username, String password) {
        try {
            Manager manager = new Manager();
            manager.setUsername(username);
            Manager managerFromDb = managerMapper.selectOne(manager);
            if(managerFromDb == null || !BCrypt.checkpw(password, managerFromDb.getPassword())){
                throw new BussinessException(403, ResultConst.INVALID_PASSWORD);
            }
            //生成jwt令牌
            return JwtUtil.createJWT(UUID.randomUUID().toString(), username,null);
        } catch (Exception e) {
            throw new BussinessException(403, ResultConst.INVALID_PASSWORD);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Integer id){
        managerMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Manager
     * @param manager
     */
    public void update(Manager manager){
        manager.setUsername(null);
        manager.setPassword(null);
        managerMapper.updateByPrimaryKeySelective(manager);
    }

    /**
     * 增加Manager
     * @param manager
     */
    public void add(Manager manager){
        Manager manager4Name = new Manager();
        manager4Name.setUsername(manager.getUsername());
        if(managerMapper.selectOne(manager4Name) != null){
            throw new BussinessException(HttpStatus.BAD_REQUEST.value(), ResultConst.USER_NAME_EXIST);
        }
        manager.setPassword(BCrypt.hashpw(manager.getPassword(), BCrypt.gensalt()));
        Long time = new Date().getTime() / 1000;
        manager.setCreateTime(time.intValue());
        managerMapper.insertSelective(manager);
    }

    /**
     * 根据ID查询Manager
     * @param id
     * @return
     */
    public Manager findById(Integer id){
        Manager manager = managerMapper.selectByPrimaryKey(id);
        manager.setPassword(null);
        return  manager;
    }
}
